﻿using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using System.Reflection;
using NHibernate.Cfg;

namespace Agr.CQRS.Infrastructure.Orm
{
    public class OrmContext 
    {
        internal static Configuration CreateConfiguration(string connectionString, params Assembly[] additionalAssembliesWithMappings)
        {
            var config = new Configuration();
            config
                .SetProperty(Environment.ProxyFactoryFactoryClass, "NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu")
                .SetProperty(Environment.ConnectionProvider, "NHibernate.Connection.DriverConnectionProvider")
                .SetProperty(Environment.ConnectionDriver, "NHibernate.Driver.SqlClientDriver")
                .SetProperty(Environment.Dialect, "NHibernate.Dialect.MsSql2000Dialect")
                .SetProperty(Environment.ConnectionString, connectionString);

            config.AddAssembly(typeof(OrmContext).Assembly);
            foreach (var a in additionalAssembliesWithMappings)
                config.AddAssembly(a);
            return config;
        }

        internal static ISessionFactory CreateSessionFactory(string connectionString, params Assembly[] additionalAssembliesWithMappings)
        {
            var config = CreateConfiguration(connectionString, additionalAssembliesWithMappings);
            return config.BuildSessionFactory();
        }

        private ISessionFactory sessionFactory;

        public OrmContext(ISessionFactory sessionFactory)
        {
            this.sessionFactory = sessionFactory;
        }

        public SessionInTransaction OpenSession()
        {
            return new SessionInTransaction(sessionFactory);
        }

        public SessionInTransaction OpenReadonlySession()
        {
            var s = new SessionInTransaction(sessionFactory);
            s.Session.FlushMode = FlushMode.Never;
            return s;
        }
    }
}
